# -*- coding: utf-8 -*-

import asyncio
import json
import time
import uuid
from centre import Centre
from log import getLogger

logger = getLogger(__name__)


lost_time = 20  # 判断断开连接的超时时间

loop = asyncio.get_event_loop()
centre = Centre(loop)

hart_list = {}


def clien_reg(user_uuid, sn):
    """
    客户端注册
    """
    if not hart_list.get(user_uuid):
        # sn = hart_list.get(user_uuid)['sn']
        logger.info(sn + ': 上线')
        centre.add_alarm_record(sn, 1)
    hart_list[user_uuid] = {
        "time": time.time(),
        "status": 1,
        "sn": sn
    }

def check_hart():
    """
    检查客户端心跳状态
    """
    while True:
        for user_uuid in hart_list:
            if abs(hart_list[user_uuid]['time'] -
                    time.time()) > lost_time:
                logger.info(user_uuid + ': 断开')
                hart_list[user_uuid]['status'] = 0
                del hart_list[user_uuid]
                centre.add_alarm_record(hart_list[user_uuid]['sn'], 2)
                break
            else:
                hart_list[user_uuid]['status'] = 1
                # logger.info(sn + '正常')
        time.sleep(5)